package com.lvmama.sync.controller.template;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.lvmama.comm.bee.service.sync.SyncBaseExecuteService;
import com.lvmama.comm.bee.service.sync.SyncBaseNewService;
import com.lvmama.comm.bee.service.sync.SyncDataSourceService;
import com.lvmama.comm.bee.service.sync.SyncElasticsearchService;
import com.lvmama.comm.bee.service.sync.SyncJarResourceService;
import com.lvmama.comm.bee.service.sync.SyncNewException;
import com.lvmama.comm.pet.po.perm.PermUser;
import com.lvmama.comm.pet.po.pub.ComLog;
import com.lvmama.comm.pet.service.pub.ComLogService;
import com.lvmama.comm.sync.po.SyncDataSource;
import com.lvmama.comm.sync.po.SyncElasticsearch;
import com.lvmama.comm.sync.po.SyncJarResource;
import com.lvmama.comm.sync.pojo.SyncTemplate;
import com.lvmama.comm.sync.pojo.SyncTemplateSql;
import com.lvmama.comm.sync.pojo.SyncTrigger;
import com.lvmama.comm.sync.utils.Constant;
import com.lvmama.comm.sync.utils.DateUtil;
import com.lvmama.comm.sync.utils.Page;
import com.lvmama.comm.sync.pojo.Template;
import com.lvmama.comm.sync.pojo.TemplatesRoot;
import com.lvmama.comm.utils.InternetProtocol;
import com.lvmama.sync.controller.base.BaseController;




@Controller
@RequestMapping(value="/sync")
public class SyncTemplateController extends BaseController {
	private static final Log logger = LogFactory.getLog(SyncTemplateController.class);
    
	@Autowired
	private SyncBaseNewService syncBaseNewService;
	
	@Autowired
	private SyncBaseExecuteService syncBaseExecuteService;
	
	@Autowired
	private SyncDataSourceService syncDataSourceService;
	
	@Autowired
	private SyncJarResourceService syncJarResourceService;
	
	@Autowired
	private SyncElasticsearchService syncElasticsearchService;
	
	@Autowired
	private ComLogService comLogService;//日志操作
	

	
	
	
	@RequestMapping("indexJar")
	public String indexJar() {
		
		return "sync/sync_template_jar";
	}

	@RequestMapping("querySyncTemplateSql")
	@ResponseBody
	public Map<String,Object> querySyncTemplateSql(Long templateSqlId) {
		Map<String,Object> map = new HashMap<String, Object>();
		if (templateSqlId == null) {
			throw new RuntimeException("templateSqlId is null");
		}
		SyncTemplateSql sql = syncBaseNewService.findSyncTemplateSqlById(templateSqlId);
		if (sql == null) {
			throw new RuntimeException("can not find templateSql by id = " + templateSqlId);
		}
		
		map.put("sql", sql);
		return map;
	}
	
	@RequestMapping("saveSyncTemplateSql")
	@ResponseBody
	public Map<String,Object> saveSyncTemplateSql(Long templateId,String testSourceId,String testFieldOne,String  testFieldTwo,String testFieldThree,SyncTemplateSql templateSql,RedirectAttributes attr ) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		if (templateSql.getTemplateSqlId() != null) {
			syncBaseNewService.updateSyncTemplateSql(templateSql);
			//insertComLog("修改了模板脚本，"+templateSql.getDescription(), templateId,templateSql);
		} else {
			templateSql.setTemplateId(templateId);
			syncBaseNewService.saveSyncTemplateSql(templateSql);
			//insertComLog("增加了模板脚本，"+templateSql.getDescription(), templateId,templateSql);
		}
		//templateId = templateSql.getTemplateId();
		result.put("templateId", templateId);
		result.put("testSourceId", testSourceId);
		result.put("testFieldOne", testFieldOne);
		result.put("testFieldTwo", testFieldTwo);
		result.put("testFieldThree", testFieldThree);

		//return "redirect:editSyncTemplate";
		return result;
	}
	
	@RequestMapping("syncTemplateList")
	public String syncTemplateList(Page page,SyncTemplate syncTemplate,Model model,HttpServletRequest request) {
		try{
			if(null==page){
				page = getPage();
			}
			Map<String,Object> map = buildParam(request);
			page.setTotalResult(syncBaseNewService.countSyncTemplateByCondition(map).intValue());
			map.put("page", page);
			List<SyncTemplate> syncTemplatelist = syncBaseNewService.findSyncTemplatePageListByCondition(map);
			model.addAttribute("syncTemplate",syncTemplate);
			model.addAttribute("syncTemplatelist",syncTemplatelist);
			model.addAttribute("dsMap",initDsMap());
			model.addAttribute("statusMap",initStatusMap());
			model.addAttribute("scriptMap",initScriptMap());
			model.addAttribute("sqlContent",request.getParameter("sqlContent"));

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return "sync/sync_template_list";
	}
	
	public Map<String, String>initDsMap(){
		Map<String, String> dsMap = new LinkedHashMap<String, String>();
		dsMap.put("","请选择");
		List<SyncDataSource> dataSources = syncDataSourceService.findAll();
		for (SyncDataSource syncDataSource : dataSources) {
			dsMap.put(syncDataSource.getSourceCode(), syncDataSource.getSourceName());
		}
		
	   return dsMap;
	}
	
	public Map<String, String>initStatusMap(){
		Map<String, String> statusMap = new LinkedHashMap<String, String>();
		statusMap.put("","请选择");
		statusMap.put("true","启用");
		statusMap.put("false","停用");
				
	   return statusMap;
	}
	
	public Map<String, String>syncStatuMap(){
		Map<String, String> statusMap = new LinkedHashMap<String, String>();
		statusMap.put("","请选择");
		Constant.SYNC_STATUS[] statuValues = Constant.SYNC_STATUS.values();
		for (Constant.SYNC_STATUS sv : statuValues) {
			statusMap.put(sv.getCode(),sv.getCnName());
       }
	
	   return statusMap;
	}
	
	public Map<String, String>triggerTypeMap(){
		Map<String, String> triggerTypeMap = new LinkedHashMap<String, String>();
		triggerTypeMap.put("","请选择");
		Constant.TRIGGER_TYPE[] triggerTypeValues = Constant.TRIGGER_TYPE.values();
		for (Constant.TRIGGER_TYPE sv : triggerTypeValues) {
			triggerTypeMap.put(sv.getCode(),sv.getCnName());
       }
	
	   return triggerTypeMap;
	}
	
	public Map<String, String>initScriptMap(){
		Map<String, String> scriptMap = new LinkedHashMap<String, String>();
		scriptMap.put("","请选择");
		Constant.SYNC_SCRIPT_TYPE[] scriptValues = Constant.SYNC_SCRIPT_TYPE.values();
				for (Constant.SYNC_SCRIPT_TYPE sv : scriptValues) {
					scriptMap.put(sv.getCode(),sv.getCnName());
		       }
								
	   return scriptMap;
	}


	@RequestMapping("editSyncTemplate")
	public String editSyncTemplate(Long templateId,String testSourceId,String testFieldOne,String  testFieldTwo,String testFieldThree,
			String templateName,String userName,String tableName,String dataSourceId,String status,String sqlContent,Integer currentPage,Integer showCount,Model model) {
		SyncTemplate template= null;
		if (templateId != null) {
			template = syncBaseNewService.findSyncTemplateById(templateId);
			model.addAttribute("syncTemplate", template);
			initTemplateSqls(templateId, sqlContent,model);
			
		}else{
			 template = new SyncTemplate();			
		}
		model.addAttribute("syncTemplate", template);
		model.addAttribute("dsMap",initDsMap());
		model.addAttribute("statusMap",initStatusMap());
		model.addAttribute("scriptMap",initScriptMap());
		model.addAttribute("templateId", templateId);

		
		model.addAttribute("testSourceId",testSourceId);
		model.addAttribute("testFieldOne",testFieldOne);
		model.addAttribute("testFieldTwo",testFieldTwo);
		model.addAttribute("testFieldThree",testFieldThree);
		
		model.addAttribute("templateName",templateName);
		model.addAttribute("userName",userName);
		model.addAttribute("tableName",tableName);
		model.addAttribute("dataSourceId",dataSourceId);
		model.addAttribute("status",status);
		model.addAttribute("sqlContent",sqlContent);

		if(null!=currentPage&&null!=showCount){
			model.addAttribute("currentPage",currentPage);
			model.addAttribute("showCount",showCount);
		}
		

		return "sync/sync_template_edit";
	}
	
	@RequestMapping("findSyncTriggerList")
	public String findSyncTriggerList(Page page,SyncTrigger syncTrigger,Long templateId,Model model,HttpServletRequest request) {
		if(null==page){
			page = getPage();
		}
		SyncTemplate template= null;
		List<SyncTrigger> syncTriggerList = new ArrayList<SyncTrigger>();
		if (templateId != null) {
			template = syncBaseNewService.findSyncTemplateById(templateId);
			if(template!=null){
				syncTrigger.setDataSourceId(template.getDataSourceId());
				syncTrigger.setUserName(template.getUserName());
				syncTrigger.setTableName(template.getTableName());
				if(syncTrigger.getpLevel()==null){
					syncTrigger.setpLevel(0l);
				}
				
				if(StringUtils.isEmpty(syncTrigger.getServerName())){
					String serverName = Constant.getInstance().getServerName();
					syncTrigger.setServerName(serverName);
				}
				
			}
			Map<String,Object> params=buildSyncTrigerParam(syncTrigger, request);
			page.setTotalResult(syncBaseNewService.countSyncTrigger(params).intValue());
            page.getPageStr();
			params.put("page", page.getCurrentPage()>0?page.getCurrentPage()-1:page.getCurrentPage());
			params.put("rows", page.getShowCount());
			syncTriggerList =syncBaseNewService.queryTriggerListPage(params);
		}else{
			 template = new SyncTemplate();			
		}
		
		model.addAttribute("syncTriggerList",syncTriggerList);
		model.addAttribute("page", page);

		model.addAttribute("dsMap",initDsMap());
		model.addAttribute("syncStatuMap",syncStatuMap());
		model.addAttribute("triggerTypeMap",triggerTypeMap());

		
		model.addAttribute("scriptMap",initScriptMap());
		model.addAttribute("templateId", templateId);

		return "sync/sync_trigger_list";
	}
	private Map<String,Object> buildSyncTrigerParam(SyncTrigger syncTrigger,HttpServletRequest request) {
	    Map<String,Object> map = new HashMap<String, Object>();
	    if(StringUtils.isNotEmpty(syncTrigger.getStatus())){
		    map.put("status", syncTrigger.getStatus());
	    }
	    
	    if(StringUtils.isNotEmpty(syncTrigger.getTriggerType())){
		    map.put("triggerType", syncTrigger.getTriggerType());
	    }

	    if(StringUtils.isNotEmpty(syncTrigger.getServerName())){
		    map.put("serverName", syncTrigger.getServerName());
	    }

	    if(StringUtils.isNotEmpty(syncTrigger.getTableName())){
			map.put("tableName", syncTrigger.getTableName());
	    }
		
	    if(StringUtils.isNotEmpty(syncTrigger.getDataSourceId())){
			map.put("dataSourceId", syncTrigger.getDataSourceId());			
	    }
	
	    if(StringUtils.isNotEmpty(syncTrigger.getUserName())){
			map.put("userName", syncTrigger.getUserName());

	    }
	
		if(null!=syncTrigger.getpLevel()){
			map.put("pLevel", syncTrigger.getpLevel());
		}
		
		
		if(StringUtils.isNotEmpty(syncTrigger.getPkValue())){
			map.put("pkValue", syncTrigger.getPkValue());
		}

		if(StringUtils.isNotEmpty(syncTrigger.getPkBegin())){
			map.put("pkBegin", syncTrigger.getPkBegin());
		}

	return map;
}
	
	private void initTemplateSqls(Long templateId,String sqlContent,Model model) {
		List<SyncTemplateSql> insertTargetSqls =null;
		List<SyncTemplateSql> sourceSqls =null; ;
		List<SyncTemplateSql> updateTargetSqls =null;;
		List<SyncTemplateSql> deleteTargetSqls =null;;
		List<SyncTemplateSql> sqls = syncBaseNewService.findSyncTemplateSqlListByTemplateId(templateId);
		for (SyncTemplateSql sql : sqls) {
			if(StringUtils.isNotEmpty(sqlContent)&&StringUtils.isNotEmpty(sqlContent.trim())&&sql.getSqlContent().toLowerCase().contains(sqlContent.toLowerCase())){
				sql.setMatch("true");
			}
			if (Constant.SYNC_SQL_TYPE.SOURCE.name().equals(sql.getSqlType())) {
				if (sourceSqls == null) {
					sourceSqls = new ArrayList<SyncTemplateSql>();
				}
				sourceSqls.add(sql);
		
			} else {
				if (Constant.TRIGGER_TYPE.INSERT.name().equals(sql.getTriggerType())) {
					if (insertTargetSqls == null) {
						insertTargetSqls = new ArrayList<SyncTemplateSql>();
					}
					insertTargetSqls.add(sql);
				} else if (Constant.TRIGGER_TYPE.UPDATE.name().equals(sql.getTriggerType())) {
					if (updateTargetSqls == null) {
						updateTargetSqls = new ArrayList<SyncTemplateSql>();
					}
					updateTargetSqls.add(sql);
				} else {
					if (deleteTargetSqls == null) {
						deleteTargetSqls = new ArrayList<SyncTemplateSql>();
					}
					deleteTargetSqls.add(sql);
				}
			}
		}

		model.addAttribute("insertTargetSqls", insertTargetSqls);
		model.addAttribute("sourceSqls", sourceSqls);
		model.addAttribute("updateTargetSqls", updateTargetSqls);
		model.addAttribute("deleteTargetSqls", deleteTargetSqls);
	}
	
	
	
	@RequestMapping("testSyncTemplateSql")
	@ResponseBody
	public Map<String,Object> testSyncTemplateSql(Long templateSqlId,String testSourceId,String testFieldOne,String  testFieldTwo,String testFieldThree,HttpServletRequest request,HttpServletResponse response) {
		if (templateSqlId == null) {
			throw new RuntimeException("templateSqlId is null");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("suc", true);
		try {
			SyncTrigger trigger = new SyncTrigger();
			trigger.setPkValue(testSourceId);
			trigger.setFieldOne(testFieldOne);
			trigger.setFieldTwo(testFieldTwo);
			trigger.setFieldThree(testFieldThree);
			int count = syncBaseExecuteService.testSyncTemplateSql(templateSqlId, trigger);
			SyncTemplateSql sql = syncBaseNewService.findSyncTemplateSqlById(templateSqlId);
			insertComLog(request,response,"测试了该模板:"+sql.getDescription()+"---PkValue:"+testSourceId, sql.getTemplateId(),sql);
			map.put("count", count);
		} catch (SyncNewException e) {
			map.put("suc", false);
			map.put("message", e.getMessage());
		}
		return map;
	}
	
	@RequestMapping("deleteSyncTemplateSql")
	@ResponseBody
	public Map<String,Object> deleteSyncTemplateSql(Long templateSqlId,HttpServletRequest request,HttpServletResponse response) {
		if (templateSqlId == null) {
			throw new RuntimeException("templateSqlId is null");
		}
		SyncTemplateSql sql = syncBaseNewService.findSyncTemplateSqlById(templateSqlId);
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("suc", true);
		if (sql != null) {
			boolean suc = true;
			if (Constant.SYNC_SQL_TYPE.SOURCE.name().equals(sql.getSqlType())) {
				boolean using = syncBaseNewService.checkSourceSyncTemplateSql(templateSqlId);
				if (using) {
					suc = false;
					result.put("message", "该源SQL正在使用中，请先删除相应目标SQL");
				}
			}
			if (suc) {
				syncBaseNewService.deleteSyncTemplateSqlById(templateSqlId);
				insertComLog(request,response,"删除了模板脚本，"+sql.getDescription(), sql.getTemplateId(),sql);
			}
			result.put("suc", suc);
		}
		return result;
	}
	
	@RequestMapping("saveSyncTemplate")
	public String saveSyncTemplate(SyncTemplate syncTemplate,Model model,HttpServletRequest request,HttpServletResponse response) {
		String message;
		try {
			if (syncTemplate.getTemplateId() == null) {
				syncTemplate = syncBaseNewService.saveSyncTemplate(syncTemplate);
				insertComLog(request,response,"新增模板", syncTemplate.getTemplateId(),null);
				message = "模板添加成功";
			} else {
				syncBaseNewService.updateSyncTemplate(syncTemplate);
				message = "模板修改成功";
				initTemplateSqls(syncTemplate.getTemplateId(),"",model);
				insertComLog(request,response,"修改模板", syncTemplate.getTemplateId(),null);
			}
		} catch (Exception e) {
			message = e.getMessage();
		}
		if (message == null) {
			message = "系统异常";
		}
		message = message.replace("\n", "\\n");
		model.addAttribute("message", message);
		model.addAttribute("syncTemplate", syncTemplate);
		model.addAttribute("dsMap",initDsMap());
		model.addAttribute("statusMap",initStatusMap());
		model.addAttribute("scriptMap",initScriptMap());
		model.addAttribute("templateId", syncTemplate.getTemplateId());


		return "sync/sync_template_edit";
	}
	
	@RequestMapping("exportTemplates")
	public void exportTemplates(String selects ,HttpServletRequest request,HttpServletResponse response) throws Exception {
		List<String> templateIds = Arrays.asList(selects.split(","));
		List<SyncTemplate> templates = syncBaseNewService.findSyncTemplateListBySelects(templateIds);
		TemplatesRoot root = new TemplatesRoot();
		root.setTemplates(new ArrayList<Template>());
		for (SyncTemplate temp : templates) {
			List<SyncTemplateSql> sqls = syncBaseNewService.findSyncTemplateSqlListByTemplateId(temp.getTemplateId());
			Template template = Template.createInstance(temp, sqls);
			root.getTemplates().add(template);
			insertComLog(request,response,"导出了模板", temp.getTemplateId(),null);
		}
		response.setContentType("application/x-download");
		response.addHeader("Content-Disposition","attachment;filename=Templates_" + new SimpleDateFormat("yyyy/MM/dd-hh:mm").format(new Date()) + ".xml");
		root.response(response.getOutputStream());
	}
	
	@RequestMapping("deleteTemplates")
	@ResponseBody
	public Map<String,Object> deleteTemplates(String selects ,HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			List<String> templateIds = Arrays.asList(selects.split(","));
			for (int i = 0; i < templateIds.size(); i++) {
				syncBaseNewService.deleteTemplateById(Long.parseLong(templateIds.get(i)));
			}
		} catch (Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		return result;
	}
	
	@RequestMapping("importTemplates")
	@ResponseBody
	public Map<String,Object> importTemplates(MultipartFile upload,Model model,HttpServletRequest request,HttpServletResponse response) {
		Map<String,Object> result = new HashMap<String, Object>();
		String message="";
		try{
			TemplatesRoot root = null;
			InputStream is = null;
			try {
				is = upload.getInputStream();
				root = TemplatesRoot.getInstance(is);
			} catch (Exception e) {
				e.printStackTrace();
				message = "导入文件有误！";
			} finally {
				IOUtils.closeQuietly(is);
			}
			
			if (root != null) {
				int updateCount = 0;
				int insertCount = 0;
				for (Template temp : root.getTemplates()) {
					temp.setTemplateId(null);
					SyncTemplate old = syncBaseNewService.findSyncTemplateByUniqueKey(temp);
					if (old == null) {
						old = syncBaseNewService.saveSyncTemplate(temp);
						insertComLog(request,response,"导入了模板", old.getTemplateId(),null);
						insertCount++;
					} else {
						temp.setTemplateId(old.getTemplateId());
						syncBaseNewService.updateSyncTemplate(temp);
						old = temp;
						updateCount++;
						insertComLog(request,response,"导入了模板,原来已存在,进行了修改。", old.getTemplateId(),null);
					}
					syncBaseNewService.deleteSyncTemplateSqlByTemplateId(old.getTemplateId());
					Map<String, String> keyMapping = new HashMap<String, String>();
					for (SyncTemplateSql sql : temp.getSourceSqls()) {
						Long oldSqlId = sql.getTemplateSqlId();
						sql.setTemplateSqlId(null);
						sql.setTemplateId(old.getTemplateId());
						Long newSqlId = syncBaseNewService.saveSyncTemplateSql(sql);
						keyMapping.put(oldSqlId.toString(), newSqlId.toString());
					}
					for (SyncTemplateSql sql : temp.getTargetSqls()) {
						sql.setTemplateSqlId(null);
						sql.setTemplateId(old.getTemplateId());
						sql.setSourceSqlId(keyMapping.get(sql.getSourceSqlId()));
						syncBaseNewService.saveSyncTemplateSql(sql);
					}
				}
				message = "更新模板" + updateCount + "条，新增模板" + insertCount + "条。";
			}
			
		}catch(Exception e){
			e.printStackTrace();
			message ="导入失败!";
		}
		
		model.addAttribute("message", message);
		result.put("message", message);
		
		return result;
	}
	
	
	@RequestMapping("importJar")
	@ResponseBody
	public Map<String,Object> importJar(MultipartFile uploadJar,String consumerName,Model model,HttpServletRequest request) {
		Map<String,Object> result = new HashMap<String, Object>();
		String message="";
		result.put("success", "true");
		if(null!=uploadJar){
			try{
				String jarOriginalName = uploadJar.getOriginalFilename();
				SyncJarResource _syncJarResource = syncJarResourceService.findByJarOriginalName(jarOriginalName);
				String jarName= jarOriginalName.substring(0,(jarOriginalName.length()-4))+"-"+(System.currentTimeMillis())+".jar";

				if(consumerName.indexOf(".xml")<0){
					consumerName =consumerName+".xml";
				}
				//jar 重新上传修改
				if(_syncJarResource!=null){
					_syncJarResource.setJarConsumerFileName(consumerName);
					_syncJarResource.setJarFile(InputStreamTOByte(uploadJar.getInputStream()));
					_syncJarResource.setJarName(jarName);
					syncJarResourceService.update(_syncJarResource);
				}else{
					SyncJarResource syncJarResource = new SyncJarResource();
					//上传jar
					
					syncJarResource.setJarConsumerFileName(consumerName);
					syncJarResource.setJarName(jarName);
					syncJarResource.setJarOriginalName(jarOriginalName);
					syncJarResource.setJarFile(InputStreamTOByte(uploadJar.getInputStream()));
					syncJarResourceService.save(syncJarResource);
				}
				
				
				
			}catch(Exception e){
				result.put("success", "false");
				message ="导入失败!";
				logger.error(e.getMessage(), e);
			}
		}else{
			result.put("success", "false");
			message ="请选择jar!";
		}
		
		model.addAttribute("message", message);
		result.put("message", message);
		
		return result;
	}
	
	@RequestMapping("changeSyncTemplateStatus")
	@ResponseBody
	public Map<String,Object> changeSyncTemplateStatus(Long templateId,HttpServletRequest request,HttpServletResponse response) {
		SyncTemplate template =null;
		if (templateId != null) {
			template = syncBaseNewService.findSyncTemplateById(templateId);
		}
		if (template == null) {
			throw new RuntimeException("template is null");
		}
		if ("true".equals(template.getStatus())) {
			template.setStatus("false");
			insertComLog(request,response,"修改了模板状态，原来为启用，修改为关闭", templateId,null);
		} else {
			template.setStatus("true");
			insertComLog(request,response,"修改了模板状态，原来为关闭，修改为启用", templateId,null);
		}
		syncBaseNewService.updateSyncTemplate(template);
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("status", template.getStatus().equals("true"));
		return result;
	}
	
	@RequestMapping("saveDataSource")
	@ResponseBody
	public Map<String,Object> saveDataSource(SyncDataSource syncDataSource){
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			if(syncDataSource != null&& syncDataSource.getSourceType().equals("oracle")){
				syncDataSource.setDriveClass("oracle.jdbc.driver.OracleDriver");
			}if(syncDataSource != null&& syncDataSource.getSourceType().equals("mysql")){
				syncDataSource.setDriveClass("com.mysql.jdbc.Driver");
			}
			if(syncDataSource.getSourceId()==null){
				syncDataSourceService.save(syncDataSource);
			}else{
				syncDataSourceService.update(syncDataSource);
			}
		}catch(SyncNewException e1){
			result.put("success", "false");
			result.put("message", e1.getMessage());
		}catch(Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		return result;
		
	}
	
	@RequestMapping("saveSyncEs")
	@ResponseBody
	public Map<String,Object> saveSyncEs(SyncElasticsearch syncElasticsearch){
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			SyncElasticsearch elasticsearch = syncElasticsearchService.findByEsCode(syncElasticsearch.getEsCode());
			if(syncElasticsearch.getId()==null){
				if(elasticsearch==null){
					syncElasticsearchService.save(syncElasticsearch);
				}else{
					result.put("success", "false");
					result.put("message", "esCode已配置,请修改!");
					return result;
				}
			}else{
				if(elasticsearch.getId().intValue() != syncElasticsearch.getId().intValue()&&elasticsearch.getEsCode().equals(syncElasticsearch.getEsCode())){
					result.put("success", "false");
					result.put("message", "esCode已配置,请修改!");
					return result;
				}
				syncElasticsearchService.update(syncElasticsearch);
			}
		}catch(SyncNewException e1){
			result.put("success", "false");
			result.put("message", e1.getMessage());
		}catch(Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		return result;
		
	}

	@RequestMapping("testDataSource")
	@ResponseBody
	public Map<String,Object> testDataSource(SyncDataSource syncDataSource){
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			
			// 创建BasicDataSource对象
		    BasicDataSource ds = new BasicDataSource();
		    if(syncDataSource != null&& syncDataSource.getSourceType().equals("oracle")){
				syncDataSource.setDriveClass("oracle.jdbc.driver.OracleDriver");
			}if(syncDataSource != null&& syncDataSource.getSourceType().equals("mysql")){
				syncDataSource.setDriveClass("com.mysql.jdbc.Driver");
			}
		    ds.setDriverClassName(syncDataSource.getDriveClass());
		    ds.setUrl(syncDataSource.getJdbcUrl());
		    ds.setUsername(syncDataSource.getUserName());
		    ds.setPassword(syncDataSource.getPassword());
		    ds.setInitialSize(10);
		    ds.setMaxActive(10);
		    ds.setMaxIdle(10);
		    ds.setMaxWait(10000);
		    if(null==ds.getConnection()){
		    	result.put("success", "false");
		    }
		} catch (Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		return result;
		
	}
	 
	
	@RequestMapping("findBySourceCode")
	@ResponseBody
	public Map<String,Object> findBySourceCode(String  sourceCode){
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			List<SyncDataSource> syncDataSource = syncDataSourceService.findBySourceCode(sourceCode);
			if(null!=syncDataSource&&syncDataSource.size()>0){
				syncDataSource.get(0).setPassword("");
				result.put("syncDataSource", syncDataSource.get(0));
			}
			
		} catch (Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		return result;
		
	}
	
	@RequestMapping("findEsById")
	@ResponseBody
	public Map<String,Object> findEsById(Long  id){
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		try {
			SyncElasticsearch syncElasticsearch =  syncElasticsearchService.findById(id);
			result.put("syncElasticsearch", syncElasticsearch);
		} catch (Exception e) {
			result.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		return result;
		
	}
	
	
	public void insertComLog(HttpServletRequest request,HttpServletResponse response,String operator,Long  templateId,SyncTemplateSql templateSql){
		PermUser permUser = getSessionUser(request,response);
		ComLog log = new ComLog();
	
		log.setObjectId(templateId);
		log.setContent(operator);
		log.setObjectType("SYNCTEMPLATE");
		log.setParentType("IP:"+InternetProtocol.getRemoteAddr(getRequest()));
		log.setOperatorName("用户名:"+(permUser == null?"":permUser.getRealName()));
		if(null!=templateSql){
			log.setLogName("操作模板脚本:"+templateSql.getDescription());
		}
		
		comLogService.addComLog(log);
	}
	
	@RequestMapping("findSyncTemplateById")
	@ResponseBody
	public Map<String,Object> findSyncTemplateById(Long templateId) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", "true");
		if (templateId == null) {
			map.put("success", "false");
		}
		SyncTemplate syncTemplate = syncBaseNewService.findSyncTemplateById(templateId);
		
		map.put("syncTemplate", syncTemplate);
		map.put("serverName", Constant.getInstance().getServerName());

		return map;
	}
	
	@RequestMapping("saveSyncTrigger")
	@ResponseBody
	public Map<String,Object> saveSyncTrigger(SyncTrigger syncTrigger) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", "true");
		
		try {
			if(!(StringUtils.isEmpty(syncTrigger.getPkBegin())&&StringUtils.isEmpty(syncTrigger.getPkValue()))){
				syncTrigger.setStatus("INIT");
				syncTrigger.setCreateTime(new Date());
				if(StringUtils.isNotEmpty(syncTrigger.getPkBegin())){
					syncTrigger.setPkValue(syncTrigger.getPkBegin());
				}
				syncBaseNewService.saveSyncTrigger(syncTrigger);
			}else{
				map.put("success", "false");
				map.put("message", "请输入PkValue或者PkBegin!");

			}
			
		}catch(SyncNewException e1){
			map.put("success", "false");
			map.put("message", e1.getMessage());
		}catch (Exception e) {
			map.put("success", "false");
			logger.error(e.getMessage(), e);
		}
		
		map.put("syncTrigger", syncTrigger);

		return map;
	}
	
	@RequestMapping("syncDataSourceList")
	public String syncDataSourceList(Page page,SyncDataSource syncDataSource,String flag,Model model,HttpServletRequest request) {
		try{
			if(null==page){
				page = getPage();
			}
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("sourceName", syncDataSource.getSourceName());
			param.put("sourceCode", syncDataSource.getSourceCode());

			page.setTotalResult(syncDataSourceService.count(param).intValue());
			param.put("page", page);
			List<SyncDataSource> syncDataSourceList = syncDataSourceService.findPageListByCondition(param);
			model.addAttribute("syncDataSource",syncDataSource);
			model.addAttribute("syncDataSources",syncDataSourceList);
			model.addAttribute("dsMap",initDsMap());
			model.addAttribute("statusMap",initStatusMap());
			model.addAttribute("scriptMap",initScriptMap());
			model.addAttribute("flag",flag);

			if(StringUtils.isNotEmpty(flag)&&flag.equals("2")){
				page.setTotalResult(syncElasticsearchService.count(param).intValue());
			}
			List<SyncElasticsearch> syncElasticsearchList = syncElasticsearchService.findPageListByCondition(param);
			model.addAttribute("syncElasticsearchList",syncElasticsearchList);

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return "sync/sync_dataSource_list";
	}
	
	
	
	@RequestMapping("findSyncLogIndex")
	public String findSyncLogIndex(Page page,String objectId,String objectType,Model model,HttpServletRequest request) {
		try{
			if(null==page){
				page = getPage();
			}
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("objectId", objectId);
			param.put("objectType", objectType);
			logger.info(comLogService.queryByObjectIdMapCount(param));
			page.setTotalResult(comLogService.queryByObjectIdMapCount(param)==null?0:comLogService.queryByObjectIdMapCount(param).intValue());
			param.put("page", page);
			param.put("skipResults",page.getStartRows()-1);
			param.put("maxResults",page.getEndRows());
			List<ComLog>  comLogList = comLogService.queryByObjectIdMap(param);
			model.addAttribute("objectId",objectId);
			model.addAttribute("objectType",objectType);
			model.addAttribute("comLogList",comLogList);

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return "sync/sync_log";
	}
	
	@RequestMapping("findSyncLog")
	@ResponseBody
	public Map<String,Object> findSyncLog(String objectId,String objectType,Model model,HttpServletRequest request,  Integer page2) {
		Map<String,Object> map = new HashMap<String, Object>();
		List<ComLog>  comLogList = new ArrayList<ComLog>();
		Page page = getPage();
		try{
			page.setCurrentPage(page2);
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("objectId", objectId);
			param.put("objectType", objectType);
			page.setTotalResult(comLogService.queryByObjectIdMapCount(param)==null?0:comLogService.queryByObjectIdMapCount(param).intValue());
			logger.info("param:"+param.toString()+" *** sync log count :"+page.getTotalResult());
			if(!page.getTotalResult().equals(0)){
				param.put("page", page);
				param.put("skipResults",page.getStartRows()-1);
				param.put("maxResults",page.getEndRows());
				comLogList = comLogService.queryByObjectIdMap(param);
				for (ComLog comLog : comLogList) {
					comLog.setMemo(DateUtil.formatDate(comLog.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				}
				logger.info("param:"+param.toString()+ "*** sync log list size :"+comLogList.size());
			}
			

		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("objectId", objectId);
		map.put("objectType", objectType);
		map.put("comLogList", comLogList);
		map.put("page2", page.getCurrentPage());
		map.put("pageCount2", page.getTotalPage());

		return map;
	}
	
	@RequestMapping("queryInitStatusCount") 
	@ResponseBody
	public Map<String,Object> queryInitStatusCount(Long templateId) { 
		Map<String,Object> map = new HashMap<String, Object>();
		    SyncTemplate template = null;
			if (templateId != null) { 
			  template = syncBaseNewService.findSyncTemplateById(templateId); 
			} 
			Integer count = 0; 
			if (template != null) { 
			Map<String, Object> params = new HashMap<String, Object>(); 
			params.put("userName", template.getUserName()); 
			params.put("tableName", template.getTableName()); 
			params.put("dataSourceId", template.getDataSourceId()); 
			count = syncBaseNewService.getInitStatusTriggerCount(params); 
			} 
			
			map.put("count", count); 
			return map;
	}
	
	@RequestMapping("deleteEs") 
	@ResponseBody
	public Map<String,Object> deleteEs(Long id) { 
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", "true");
			try {
				syncElasticsearchService.deleteById(id);
			} catch (Exception e) {
				map.put("success", "false");
			}
			return map;
	}
	
	
	@RequestMapping("deleteDataSource") 
	@ResponseBody
	public Map<String,Object> deleteDataSource(Long sourceId) { 
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", "true");
			try {
				syncDataSourceService.deleteById(sourceId);
			} catch (Exception e) {
				map.put("success", "false");
			}
			return map;
	}
	
	@RequestMapping("resortSyncTemplateSql")
	@ResponseBody
	public Map<String,Object> resortSyncTemplateSql(Long templateId,Long templateSqlId, String direction) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("success", "true");
		if (templateId != null) {
			if (templateSqlId != null && direction != null) {
				syncBaseNewService.resortSyncTemplateSql(templateSqlId, direction);
			}
		}
		result.put("templateId", templateId);
		
		return result;
	}
	
	private Map<String,Object> buildParam(HttpServletRequest request) {
		    Map<String,Object> map = new HashMap<String, Object>();
		    
			map.put("templateName", request.getParameter("templateName"));			
		
			map.put("dataSourceId", request.getParameter("dataSourceId"));			
		
			map.put("userName", request.getParameter("userName"));
		
			map.put("tableName",request.getParameter("tableName") );
	
			map.put("status",request.getParameter("status"));
			
			map.put("sqlContent",request.getParameter("sqlContent"));
			
		return map;
	}

	

	public ComLogService getComLogService() {
		return comLogService;
	}

	public void setComLogService(ComLogService comLogService) {
		this.comLogService = comLogService;
	}

	/**  
     * 将InputStream转换成byte数组  
     * @param in InputStream  
     * @return byte[]  
     * @throws IOException  
     */  
    public static byte[] InputStreamTOByte(InputStream in) throws IOException{  
          
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[4096];  
        int count = -1;  
        while((count = in.read(data,0,4096)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return outStream.toByteArray();  
    } 
	
	public static void main(String[] args) {
		String name = "spring-config-dubbo-prism-service-consumer.xml";
		name= name.substring(0,(name.length()-4))+"-"+(System.currentTimeMillis())+".xml";
		System.out.println(name);
		
	}
}
	
 